package com.webservice.command.utils;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;

/**
 * 数组工具类
 * @author 潘保涛
 *
 */
public class ByteArrayUtil {
	
	/**
	 * 数组相加
	 * 例如：
	 * byte1: [49, 50, 51]
	 * byte2: [52, 53, 54]
	 * newByte: [49, 50, 51, 52, 53, 54]
	 * @param arrayObj1
	 * @param arrayObj2
	 * @return
	 */
	public static Object bytesAdd(Object arrayObj1, Object arrayObj2){
		
		if(arrayObj1 != null && arrayObj2 != null){
		
			Class curClazz1 = arrayObj1.getClass();
			Class curClazz2 = arrayObj2.getClass();
			
			if(!curClazz1.isArray() || !curClazz2.isArray()){
				return null;
			}else{
				Class arrayClazz = curClazz1.getComponentType();//返回表示数组组件类型的 Class
				int length1 = Array.getLength(arrayObj1);//返回当前数组的长度
				int length2 = Array.getLength(arrayObj2);//返回当前数组的长度
				int newLength = length1 + length2;
				Object newArrayObj = Array.newInstance(arrayClazz, newLength);//多态,创建新数组
				
				System.arraycopy(arrayObj1, 0, newArrayObj, 0, length1);//赋值
				System.arraycopy(arrayObj2, 0, newArrayObj, length1, length2);//赋值
				
				return newArrayObj;
			}
		}
		
		return null;
	}
	
	public static byte[] bytesAddStr(byte[] bytes, String str, String charset){
//		String targetStr = "";
		byte[] targetBytes = null;
		
		if(str != null && !str.equals("")){
			
			byte[] strBytes = null;
			try {
				strBytes = str.getBytes(charset);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			
			Object targetObj = bytesAdd(bytes, strBytes);
			if(targetObj != null){
				targetBytes = (byte[])targetObj;
			}
		}else{
			targetBytes = bytes;
		}
		
//		if(targetBytes != null){
//			targetStr = Arrays.toString(targetBytes);
//		}
		
		return targetBytes;
	}
}
